package com.manor.main.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.AppUtils
import com.google.android.material.bottomnavigation.BottomNavigationItemView
import com.google.android.material.bottomnavigation.BottomNavigationMenuView
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gyf.immersionbar.ImmersionBar
import com.huawei.hms.api.ConnectionResult
import com.huawei.hms.api.HuaweiApiClient
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.manor.common.CommonAppConfig
import com.manor.common.CommonAppContext
import com.manor.common.Constants
import com.manor.common.bean.ChatAnchorParam
import com.manor.common.bean.ChatAudienceParam
import com.manor.common.bean.ConfigBean
import com.manor.common.event.VideoPauseEvent
import com.manor.common.http.CommonHttpConsts
import com.manor.common.http.CommonHttpUtil
import com.manor.common.interfaces.CommonCallback
import com.manor.common.utils.*
import com.manor.dynamic.activity.AbsDynamicActivity
import com.manor.im.bean.ImUserBean
import com.manor.im.event.ImUnReadCountEvent
import com.manor.im.utils.PushUtils
import com.manor.main.R
import com.manor.main.adapter.MainTabAdapter
import com.manor.main.dialog.NoticeTipPopup
import com.manor.main.fragment.HomeFragment
import com.manor.main.fragment.MainPersonalCenterFragment
import com.manor.main.fragment.SVideoFragment
import com.manor.main.fragment.community.NewCircleFragment
import com.manor.main.http.MainHttpConsts
import com.manor.main.http.MainHttpUtil
import com.manor.main.utils.UpdateUtil
import com.manor.main.utils.VersionManagementUtil
import com.manor.video.utils.VideoStorge
import com.mob.adsdk.AdSdk
import com.mob.gamesdk.GameSdk
import com.orhanobut.logger.Logger
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.modules.chat.GroupChatManagerKit
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit
import com.tencent.qcloud.tim.uikit.utils.FileUtil
import com.tencent.qcloud.tim.uikit.utils.TUIKitLog
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_main_new.*
import kotlinx.android.synthetic.main.item_menu_badge.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @version 1.0
 *
 * @date 2020/4/28  15:31
 */
@Route(path = RouteUtil.PATH_MAIN)
class MainActivity : AbsDynamicActivity(), ConversationManagerKit.MessageUnreadWatcher, HuaweiApiClient.ConnectionCallbacks, HuaweiApiClient.OnConnectionFailedListener {
    private lateinit var badgeView: View
    private var menuView: BottomNavigationMenuView? = null
    private var msgTab: BottomNavigationItemView? = null
    private var svTab: MenuItem? = null

    private var mFirstLoad = false
    private var mFirstLogin = false
    private var firstPressedTime: Long = 0
    private var isPush = false
    private var client: HuaweiApiClient? = null
    private var isMainLoad = false

    private lateinit var mAdapter: MainTabAdapter


    companion object {
        val fragmentList = mutableListOf(
//                ShortFragment.newInstance(),
//                HMsgFragment.newInstance(),
                HomeFragment.newInstance(),
//                DiscoveryFragment.newInstance(),
                NewCircleFragment.newInstance(),
                SVideoFragment.newInstance(),
                MainPersonalCenterFragment.newInstance()
        )

        fun forward(context: Context) {
            forward(context, false)
        }

        fun forward(context: Context, firstLogin: Boolean) {
            val intent = Intent(context, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            intent.putExtra(Constants.FIRST_LOGIN, firstLogin)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_main_new

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Logger.e("onChatAudToAncStart onNewIntent isMainLoad=$isMainLoad")
        if (isMainLoad && ScreenUtils.isScreenLock()) {
            isMainLoad = false
        } else {
            loadIntent(intent)
        }
    }

    override fun main() {
        super.main()
        MainHttpUtil.getBaseInfo(null)

        initPush()

        navView.itemIconTintList = null
        navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
        mAdapter = MainTabAdapter(this, fragmentList)
        mViewPager.offscreenPageLimit = 3
        mViewPager.isUserInputEnabled = false
        mViewPager.adapter = mAdapter
        badgeView = LayoutInflater.from(this).inflate(R.layout.item_menu_badge, navView, false)
        menuView = navView.getChildAt(0) as BottomNavigationMenuView?
        svTab = navView.menu.findItem(R.id.navigation_video)
        msgTab = menuView?.getChildAt(3) as BottomNavigationItemView?
        msgTab?.addView(badgeView)

        EventBus.getDefault().register(this)
        checkVersion()
        CommonAppConfig.getInstance().isLaunched = true
        CommonAppConfig.getInstance().launchTime = System.currentTimeMillis() / 1000
        mFirstLoad = true

        val chatParamType = intent.getIntExtra(Constants.CHAT_PARAM_TYPE, 0)
        if (chatParamType == Constants.CHAT_PARAM_TYPE_ANC) isMainLoad = true

        loadIntent(intent)
        //checkNotify()

        AdSdk.getInstance().setUserId(CommonAppConfig.getInstance()?.uid)
        GameSdk.getInstance().setUserId(CommonAppConfig.getInstance()?.uid)

        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.gray8)
                .statusBarDarkFont(true)
                .init()

    }


    override fun onStart() {
        super.onStart()
        FileUtil.initPath()
        ConversationManagerKit.getInstance().addUnreadWatcher(this)
        GroupChatManagerKit.getInstance()
    }

    override fun onResume() {
        super.onResume()
        KLog.e("Mainactivity", "onResume")
        loginIM()
        if (is_Dialog) {
            checkPermissions()
        }

        if (mFirstLoad) {
            mFirstLoad = false
            if (!isPush) {
                navView?.selectedItemId = R.id.navigation_video
            } else {
                navView?.selectedItemId = R.id.navigation_video
            }
        }
    }



    override fun onStop() {
        ConversationManagerKit.getInstance().destroyConversation()
        super.onStop()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        MainHttpUtil.cancel(CommonHttpConsts.GET_CONFIG)
        MainHttpUtil.cancel(MainHttpConsts.CHECK_AGENT)
        CommonHttpUtil.cancel(CommonHttpConsts.SET_LOCAITON)
        MainHttpUtil.cancel(MainHttpConsts.GET_SIGN)
        //LocationUtil.getInstance().stopLocation()

        CommonAppConfig.getInstance().isLaunched = false
        VideoStorge.getInstance().clear()

        super.onDestroy()
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - firstPressedTime < 2000) {
            onStateNotSaved()
            super.onBackPressed()
            AppUtils.exitApp()
        } else {
            if (isBackVideo) {
                videoBacks()
            } else {
                Toast.makeText(this@MainActivity, "再按一次退出", Toast.LENGTH_SHORT).show()
                firstPressedTime = System.currentTimeMillis()
            }
        }
    }


    private fun initPush() {
        PushUtils.startPush(this@MainActivity)
    }

    private fun loadIntent(intent: Intent?) {
        val chatParamType = intent?.getIntExtra(Constants.CHAT_PARAM_TYPE, 0) ?: -1
        Logger.e("onChatAudToAncStart loadIntent chatParamType=$chatParamType")
        if (chatParamType == Constants.CHAT_PARAM_TYPE_ANC) {
            val param: ChatAnchorParam? = intent?.getParcelableExtra(Constants.CHAT_PARAM_ANC)
            if (param != null) {
                RouteUtil.forwardAnchorActivity(param)
            }
            val notifyUtils = INotificationUtils(CommonAppContext.sInstance)
            notifyUtils.clearNotification()
        } else if (chatParamType == Constants.CHAT_PARAM_TYPE_AUD) {
            val param: ChatAudienceParam? = intent?.getParcelableExtra(Constants.CHAT_PARAM_AUD)
            if (param != null) {
                RouteUtil.forwardAudienceActivity(param)
            }
        }

        isPush = intent?.getBooleanExtra(Constants.IS_FROM_PUSH, false) ?: false
        Logger.e("onChatAudToAncStart loadIntent isPush=$isPush")
        if (isPush) {
            val imUserBean: ImUserBean? = intent?.getParcelableExtra(Constants.USER_BEAN)
            val isFollow = intent?.getBooleanExtra(Constants.FOLLOW, false)
            val isBlack = intent?.getBooleanExtra(Constants.BLACK, false)
            val isAuth = intent?.getBooleanExtra(Constants.AUTH_STATUS, false)
            val isHome = intent?.getBooleanExtra(Constants.IM_FROM_HOME, true)
            if (imUserBean != null) {
                cleanNotify()
                //RouteUtil.forwardChatRoom(imUserBean, isFollow, isBlack, isAuth, isHome);
            } else {
                val chatAnchorParam: ChatAnchorParam? = intent?.getParcelableExtra("chatAnchorParam")
                if (chatAnchorParam != null) {
                    if (CommonAppConfig.getInstance().isLaunched) {
                        RouteUtil.forwardAnchorActivity(chatAnchorParam)
                    } else {
                        RouteUtil.forwardMainActivity(chatAnchorParam)
                    }
                }
            }
        }
    }

    private fun checkNotify() {
        if (!NotifyCheckUtil.isNotifyEnabled(this)) {
            XPopup.Builder(mContext)
                    .asConfirm("温馨提示", "为了您能顺利接收消息，我们需要您打开通知和横幅权限") {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            //暂时去除
                            //NotifyCheckUtil.goNotifyChanelIntent();
                            NotifyCheckUtil.goNotifyIntent()
                        } else {
                            NotifyCheckUtil.goNotifyIntent()
                        }
                    }
                    .show()
        }
    }

    /**
     * 检查版本更新
     */
    private fun checkVersion() {
        CommonAppConfig.getInstance().getConfig(object : CommonCallback<ConfigBean?>() {
            override fun callback(configBean: ConfigBean?) {
                if (configBean != null) {
                    val sw = SpUtils.getInstance(this@MainActivity).getInt(SpUtil.APP_MAIN_SWITCH, 0)
                            ?: 0
                    if (configBean.maintainSwitch > sw) { //开启维护
                        XPopup.Builder(mContext)
                                .hasShadowBg(true)
                                .dismissOnTouchOutside(false)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .asCustom(NoticeTipPopup(mContext, configBean.maintainTips, configBean.maintainSwitch))
                                .show()
                    }
                    if (StringUtil.isEmpty(configBean.version)) {
                        return
                    }
                    if (VersionManagementUtil.VersionComparison(configBean.version,
                                    VersionManagementUtil.getVersion(mContext)) == 1) {
                        val title = WordUtil.getString(com.manor.common.R.string.version_update)
                                ?: ""
                        val content = configBean.updateDes ?: ""
                        val apkUrl = configBean.updateUrl ?: ""
                        val versionCode = configBean.curVersionCode
                        val isForce = configBean.isForce.trim { it <= ' ' } == "1"
                        //增量更新
                        val upType = "1"
                        val patchUrl = configBean.patchUrl ?: ""
                        UpdateUtil.instance
                                .initDownload(mContext, title, content, apkUrl, versionCode, isForce, upType, patchUrl)

                        if (isForce)
                            Handler().postDelayed({
                                EventBus.getDefault().post(VideoPauseEvent(true))
                            }, 2000)

                        KLog.e("UpdateUtil", "VideoPauseEvent post+++++++++++++++")
                    }
                }
            }
        })
    }


    private fun cleanNotify() {
        val notifyUtils = INotificationUtils(CommonAppContext.sInstance)
        notifyUtils.clearNotification()
    }

    val APPLICATION_AUTHORITY = 12
    var is_Dialog = true

    /**
     * 检查权限
     */
    private fun checkPermissions() {
        is_Dialog = true
        if (!lacksPermission(this, Permission.WRITE_EXTERNAL_STORAGE)) {
            //   LocationUtil.getInstance().upLocation()
        } else {
            AndPermission.with(this)
                    .runtime()
                    .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA, Permission.RECORD_AUDIO)
                    .onGranted {
                        if (!lacksPermission(this, Permission.WRITE_EXTERNAL_STORAGE)) {

                        }

                    }
                    .onDenied { data ->

                        for (i in data.indices) {
                            KLog.e("tag", data[i] + "")
                            if (lacksPermission(this, Permission.CAMERA)) {
                                Toast.makeText(this, resources.getString(R.string.permissions_camera), Toast.LENGTH_SHORT).show()
                                if (AndPermission.hasAlwaysDeniedPermission(this, data)) {
                                    is_Dialog = false
                                    showSettingDialog(this, resources.getString(R.string.permissions_camera), 10)

                                }
                                break
                            }
                            if (lacksPermission(this, Permission.WRITE_EXTERNAL_STORAGE)) {
                                Toast.makeText(this, resources.getString(R.string.permissions_storage), Toast.LENGTH_SHORT).show()
                                if (AndPermission.hasAlwaysDeniedPermission(this, data)) {
                                    is_Dialog = false
                                    showSettingDialog(this, resources.getString(R.string.permissions_storage), 10)

                                }
                                break
                            }
                            if (lacksPermission(this, Permission.RECORD_AUDIO)) {
                                Toast.makeText(this, resources.getString(R.string.permissions_audio), Toast.LENGTH_SHORT).show()
                                if (AndPermission.hasAlwaysDeniedPermission(this, data)) {
                                    is_Dialog = false
                                    showSettingDialog(this, resources.getString(R.string.permissions_audio), 10)

                                }
                                break
                            }
                        }
                    }
                    .start()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        KLog.e("Mainactivity", "onActivityResult")
        is_Dialog = true
        when (requestCode) {
            APPLICATION_AUTHORITY -> checkPermissions()

        }
    }


    /**
     * 登录IM
     */
    private fun loginIM() {
        KLog.e("Main#loginIM", V2TIMManager.getInstance().loginStatus)
        if (V2TIMManager.getInstance().loginStatus != V2TIMManager.V2TIM_STATUS_LOGINED) {
            val uid = CommonAppConfig.getInstance().uid ?: ""
            val sign = SpUtil.getInstance().getStringValue(SpUtil.TX_IM_USER_SIGN) ?: ""
            TUIKit.login(uid, sign, object : IUIKitCallBack {
                override fun onSuccess(data: Any?) {
                    TUIKitLog.i("TUIKit", "imLogin onSuccess ")
                }

                override fun onError(module: String?, errCode: Int, errMsg: String?) {
                    TUIKitLog.i("TUIKit", "imLogin errorCode = $errCode, errorInfo = $errMsg")
                }

            })
        }


    }


    @SuppressLint("RestrictedApi")
    private fun setSvBg(isTran: Boolean, viewId: Int) {
        when (viewId) {
            R.id.navigation_video -> {
                ImmersionBar.with(this)
                        .fitsSystemWindows(true)
                        .statusBarColor(R.color.gray8)
                        .statusBarDarkFont(true)
                        .init()
            }
            R.id.navigation_square -> {
                ImmersionBar.with(this)
                        .fitsSystemWindows(true)
                        .statusBarColor(R.color.white)
                        .statusBarDarkFont(true)
                        .init()
            }
            R.id.navigation_message -> {
                ImmersionBar.with(this)
                        .fitsSystemWindows(false)
                        .transparentStatusBar()
                        .init()
            }
            R.id.navigation_mine -> {
                ImmersionBar.with(this)
                        .fitsSystemWindows(false)
                        .transparentStatusBar()
                        .statusBarDarkFont(true)
                        .init()
            }
        }

    }

    /**
     * 显示未读消息
     */
    @Deprecated("已废弃")
    private fun setUnReadCount(unReadCount: String) {
//        if (badgeView.mRedPoint != null) {
//            if ("0" == unReadCount) {
//                if (badgeView.mRedPoint.visibility == View.VISIBLE) {
//                    badgeView.mRedPoint.visibility = View.INVISIBLE
//                }
//            } else {
//                if (badgeView.mRedPoint.visibility != View.VISIBLE) {
//                    badgeView.mRedPoint.visibility = View.VISIBLE
//                }
//            }
//            badgeView.mRedPoint.text = unReadCount
//        }
    }


    private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        if (ClickUtil.canClick(400))
            when (item.itemId) {
                R.id.navigation_video -> {
                    if (mViewPager.currentItem != 0) {
                        mViewPager.setCurrentItem(0, false)
                        setSvBg(isTran = true, viewId = item.itemId)
                    }

                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_square -> {
                    if (mViewPager.currentItem != 1) {
                        mViewPager.setCurrentItem(1, false)
                        setSvBg(isTran = true, viewId = item.itemId)
                    }
                    return@OnNavigationItemSelectedListener true
                }

                R.id.navigation_message -> {
                    if (mViewPager.currentItem != 2) {
                        mViewPager.setCurrentItem(2, false)
                        setSvBg(isTran = true, viewId = item.itemId)
                    }
                    return@OnNavigationItemSelectedListener true
                }

                R.id.navigation_mine -> {
                    if (mViewPager.currentItem != 3) {
                        mViewPager.setCurrentItem(3, false)
                        setSvBg(isTran = true, viewId = item.itemId)
                    }
                    return@OnNavigationItemSelectedListener true
                }
            }
        false
    }

    override fun updateUnread(count: Int) {
//        KLog.e("Main#updateUnread", count)
//        if (badgeView.mRedPoint != null) {
//            if (count > 0) {
//                badgeView.mRedPoint.visibility = View.VISIBLE
//            } else {
//                badgeView.mRedPoint.visibility = View.INVISIBLE
//            }
//            var unreadStr = "" + count
//            if (count > 100) {
//                unreadStr = "99+"
//            }
//            badgeView.mRedPoint.text = unreadStr
//        }
    }

    override fun onConnected() {
        KLog.e("push", "HuaweiApiClient 连接成功")
    }

    override fun onConnectionSuspended(cause: Int) {
        KLog.e("push", "HuaweiApiClient 连接断开")
        client?.connect(this@MainActivity)
    }

    override fun onConnectionFailed(result: ConnectionResult?) {
        KLog.e("push", "HuaweiApiClient连接失败，错误码：" + result?.errorCode)
    }


    @Deprecated("已废弃")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onImUnReadCountEvent(e: ImUnReadCountEvent) {
        val unReadCount = e.unReadCount
        if (!TextUtils.isEmpty(unReadCount)) {
            // setUnReadCount(unReadCount)
        }
    }

    fun setToThridPart(){
        mViewPager.setCurrentItem(1, false)
    }
}